package thread;

import java.awt.Toolkit;
import java.util.LinkedList;

import bean.util.WindowUtil;
import controller.RobotController;
import controller.ToolController;

public class AutoPetThread extends Thread implements Runnable {

	private RobotController rbCtrl = null;

	private ToolController tlCtrl = new ToolController();

	public AutoPetThread() {
		if (WindowUtil.cgWins.size() > 0) {
			rbCtrl = new RobotController(WindowUtil.cgWins.get(0));
		}
	}

	public void run() {
		int oddNumber = 0;
		boolean hasLv1Pet = false;
		boolean isNewBattle = true;

		while (true) {
			if (ThreadToggle.KEEP_RUNNING) {
				int gameStatus = rbCtrl.getGameStatus();

				switch (gameStatus) {
				case RobotController.NORMAL_STATUS:
					rbCtrl.setConnect();
					oddNumber = 1 - oddNumber;
					hasLv1Pet = false;
					isNewBattle = true;

					rbCtrl.moveOnMap(RobotController.NO_DIRECTION, true);
					rbCtrl.delay(500);

					if (oddNumber == 0) {
						rbCtrl.moveOnMap(RobotController.LEFT_DIRECTION, true);
					} else {
						rbCtrl.moveOnMap(RobotController.RIGHT_DIRECTION, true);
					}

					rbCtrl.delay(1000);
					break;
				case RobotController.ROLE_WAR_STATUS:
					if (isNewBattle) {
						LinkedList<Integer> petList = tlCtrl.getLv1PetList();
						isNewBattle = false;

						for (int i : petList) {
							int[] attr = WindowUtil
									.getPetAttr(WindowUtil.petWins[i]);

							if (attr[0] == TARGET_NAME_LENGTH) {
								System.out.println(attr[1] + "\t" + attr[2]);
								if ((attr[1] >= TARGET_HP && attr[2] >= TARGET_MP)
										|| attr[1] + attr[2] >= TARGET_TOTAL) {
									hasLv1Pet = true;
								}
							}
						}
					}

					if (!hasLv1Pet) {
						rbCtrl.roleActionSelect(RobotController.ESC_ACTION);
					} else {
						Toolkit.getDefaultToolkit().beep();
						rbCtrl.delay(12000);

						rbCtrl.roleActionSelect(RobotController.DEF_ACTION);
					}

					break;
				case RobotController.UNCONNECTED_STATUS:
					rbCtrl.reconnected();

					break;
				default:
					break;
				}
			}

			rbCtrl.delay(500);
		}
	}

	private static final int TARGET_NAME_LENGTH = 2;

	private static final int TARGET_HP = 100;

	private static final int TARGET_MP = 110;

	private static final int TARGET_TOTAL = 212;

}
